<template>
	<view class="container">
		<!-- 主内容区 -->
		<scroll-view scroll-y class="main-content">
			<!-- 收货地址 -->
			<view class="address-section" @click="chooseAddress">
				<view class="section-title">
					<text>收货地址</text>
				</view>
				<view class="address-info" v-if="addressInfo">
					<text class="consignee">{{addressInfo.receive_name}} {{addressInfo.receive_phone}}</text>
					<text class="address-detail">{{addressInfo.area}}
						{{addressInfo.address}}</text>
				</view>
				<view class="no-address" v-else>
					<text>请选择地址</text>
					<text class="all-evaluate"> &gt;</text>
				</view>
			</view>

			<!-- 商品列表 -->
			<view class="goods-section">
				<view class="section-title">
					<text>商品信息</text>
				</view>
				<view class="goods-list">
					<view class="goods-item" v-for="item in goodsList" :key="item.id">
						<image :src="item.goods_info.thumb" mode="aspectFill" class="goods-image"></image>
						<view class="goods-info">
							<text class="goods-name">{{item.goods_info.goods_name}}</text>
							<text class="goods-desc">{{item.goods_info.description}}</text>
							<text class="goods-spec">{{item.goods_info.goods_attr_info.attrs}}</text>
							<view class="goods-price">
								<text class="sell-price">¥{{item.goods_info.sell_price}}</text>
								<text class="original-price"
									v-if="item.goods_info.original_price > item.goods_info.sell_price">¥{{item.goods_info.original_price}}</text>
							</view>
							<view class="goods-amount">
								<text>x{{item.cart_num}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 支付方式 -->
			<view class="payment-section">
				<view class="section-title">
					<text>支付方式</text>
				</view>
				<view class="payment-methods">
					<view class="method-item" :class="{ 'active': paymentMethod === 1 }"
						@click="selectPaymentMethod(1)">
						<image src="../../static/androidImg/icon_pay_come.png" mode="widthFix" class="method-icon">
						</image>
						<text>货到付款</text>
						<image v-if="paymentMethod === 1" src="../../static/androidImg/icon_pay_yes.png" mode="widthFix"
							class="check-icon"></image>
					</view>
					<view class="method-item" :class="{ 'active': paymentMethod === 2 }"
						@click="selectPaymentMethod(2)">
						<image src="../../static/androidImg/icon_pay_yu.png" mode="widthFix" class="method-icon">
						</image>
						<text>余额支付</text>
						<image v-if="paymentMethod === 2" src="../../static/androidImg/icon_pay_yes.png" mode="widthFix"
							class="check-icon"></image>
					</view>
					<view class="method-item" :class="{ 'active': paymentMethod === 3 }"
						@click="selectPaymentMethod(3)">
						<image src="../../static/androidImg/icon_wechat.png" mode="widthFix" class="method-icon">
						</image>
						<text>微信支付</text>
						<image v-if="paymentMethod === 3" src="../../static/androidImg/icon_pay_yes.png" mode="widthFix"
							class="check-icon"></image>
					</view>
				</view>
			</view>
			<view class="coupon-section" v-if="totalData && totalData.total_postage_money>0">
				<view class="section-title">
					<text>邮费</text>
				</view>
				<view class="coupon-info">
					<text>¥{{totalData.total_postage_money}}</text>
				</view>
			</view>
			<!-- 优惠券 -->
			<view class="coupon-section" @click="chooseCoupon">
				<view class="section-title">
					<text>使用优惠券</text>
				</view>
				<view class="coupon-info">
					<text v-if="selectedCoupon">{{selectedCoupon.name}} - ¥{{selectedCoupon.money}}</text>
					<text v-else>请选择优惠券</text>
					<text class="all-evaluate"> &gt;</text>
				</view>
				<view class="coupon-discount" v-if="totalData && totalData.first_order_discount > 0">
					<text>首单优惠 ¥{{totalData.first_order_discount}}</text>
				</view>
			</view>

		</scroll-view>

		<!-- 底部支付栏 -->
		<view class="bottom-bar">
			<view class="price-info">
				<text>总价: </text>
				<text
					class="total-price">¥{{totalData ? totalData.pay_money - (selectedCoupon ? selectedCoupon.money : 0) : 0}}</text>
				<!-- <text class="discount-price" v-if="totalData && totalData.pay_money < totalData.order_money"> 优惠后:
					¥{{totalData.pay_money}}</text> -->
			</view>
			<view class="pay-btn" @click="confirmPayment">确认支付</view>
		</view>
	</view>
</template>

<script>
	import api from '../../api/request';

	export default {
		data() {
			return {
				cartIds: '',
				goodsList: [],
				totalData: null,
				addressInfo: null,
				addressList: [], // 地址列表
				paymentMethod: 1, // 1:货到付款, 2:余额支付, 3:微信支付, 4:支付宝支付
				couponList: [],
				selectedCoupon: null,
				loading: false,
				orderNum: '' // 保存订单号
			};
		},
		onShow() {
			console.log(144)
			this.getAddressLists();
			// 如果从地址添加页面返回，检查是否有地址但未选中
			if (this.addressList && this.addressList.length > 0 && !this.addressInfo) {
				// 查找默认地址或第一个地址
				const defaultAddress = this.addressList.find(item => item.is_default === 1);
				if (defaultAddress) {
					this.addressInfo = defaultAddress;
				} else if (this.addressList.length > 0) {
					this.addressInfo = this.addressList[0];
				}
			}
		},
		onLoad(options) {

			// 监听地址选择事件
			this.addressListener = uni.$on('selectAddress', (addressId) => {
				console.log('通过事件总线接收到选中的地址ID:', addressId);
				this.setSelectedAddressId(addressId);
			});

			// 获取购物车ID
			if (options && options.cart_ids) {
				this.cartIds = options.cart_ids;
				this.loadOrderData();
			} else {
				uni.showToast({
					title: '购物车ID不存在',
					icon: 'none'
				});
			}

			// 监听优惠券选择事件
			this.couponListener = uni.$on('selectCoupon', (coupon) => {
				this.selectedCoupon = {
					id: coupon.coupon_id,
					name: coupon.coupon_name,
					money: Number(coupon.money) // 确保是数字类型
				};
				// 这里可以添加更新订单总价的逻辑
				console.log('选择的优惠券:', this.selectedCoupon);
			});
		},

		// 页面卸载时移除事件监听
		onUnload() {
			if (this.couponListener) {
				uni.$off('selectCoupon', this.couponListener);
			}
			if (this.addressListener) {
				uni.$off('selectAddress', this.addressListener);
			}
		},
		methods: {
			// 设置选中的地址ID
			setSelectedAddressId(id) {
				// 根据ID获取地址详情
				const address = this.addressList.find(item => item.id === id);
				if (address) {
					this.addressInfo = address;
					console.log('选中的地址:', this.addressInfo);
				}
			},

			// 获取地址列表
			getAddressLists() {
				api.getAddressList({
					page: 1
				}).then(res => {
					if (res.code === 1 && res.data && res.data.rows) {
						this.addressList = res.data.rows;
						// 如果是编辑订单且已有地址ID，自动选中
						if (this.addressInfo && this.addressInfo.id) {
							const selectedAddress = this.addressList.find(item => item.id === this.addressInfo.id);
							if (selectedAddress) {
								this.addressInfo = selectedAddress;
							}
						} else if (this.addressList.length > 0) {
							// 如果没有选中地址但地址列表不为空，自动选择默认地址或第一个地址
							const defaultAddress = this.addressList.find(item => item.is_default === 1);
							if (defaultAddress) {
								this.addressInfo = defaultAddress;
							} else {
								this.addressInfo = this.addressList[0];
							}
						}
					} else {
						this.addressList = [];
						this.addressInfo = null;
					}
				}).catch(err => {
					console.error('获取地址列表失败', err);
					this.addressList = [];
					this.addressInfo = null;
				});
			},
			// 加载订单数据
			loadOrderData() {
				if (this.loading) return;

				this.loading = true;

				// 调用订单数据接口
				api.cartBuyGoods({
					cart_ids: this.cartIds
				}).then(res => {
					this.loading = false;
					if (res.code === 1 && res.data) {
						this.goodsList = res.data.new_arr || [];
						this.totalData = res.data.total_data;

						// 处理商品图片路径
						this.goodsList.forEach(item => {
							if (item.goods_info && item.goods_info.thumb) {
								// 移除图片路径中的空格和多余的反斜杠
								item.goods_info.thumb = item.goods_info.thumb.replace(/`/g, '').trim();
							}
						});

						// 加载可用优惠券
						// this.loadCouponData();
					} else {
						uni.showToast({
							title: res.msg || '获取订单数据失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					this.loading = false;
					console.error('获取订单数据失败', err);
					uni.showToast({
						title: err.msg || '获取订单数据失败',
						icon: 'none'
					});
				});
			},



			// 选择支付方式
			selectPaymentMethod(method) {
				this.paymentMethod = method;
			},

			// 选择地址
			chooseAddress() {
				// 跳转到地址选择页面
				uni.navigateTo({
					url: '/pages/address/addressList'
				});
			},

			// 选择优惠券
			chooseCoupon() {
				// 跳转到优惠券选择页面，并传递来源页面参数
				// 构造商品信息参数
				const goodsData = this.goodsList.map(item => {
					return {
						goods_id: item.goods_id,
						total_money: item.goods_info.sell_price,
					};
				});
				// 使用JSON.stringify和encodeURIComponent正确传递对象数据
				uni.navigateTo({
					url: '/pages/coupon/couponList?page=sureOrder&goodsData=' + encodeURIComponent(JSON.stringify(
						goodsData))
				});
			},

			// 确认支付
			confirmPayment() {
				// 检查是否选择了地址
				if (!this.addressInfo) {
					uni.showToast({
						title: '请先选择收货地址',
						icon: 'none'
					});
					return;
				}

				// 调用支付接口
				uni.showLoading({
					title: '处理中'
				});

				// 检查是否已有订单号
				if (this.orderNum) {
					// 已有订单号，直接调用支付接口
					const addressId = this.addressInfo.id;
					const couponId = this.selectedCoupon ? this.selectedCoupon.id : 0;

					// 根据支付方式调用不同的支付接口
					if (this.paymentMethod === 1) {
						// 货到付款
						this.cashOnDelivery(this.orderNum, addressId);
					} else if (this.paymentMethod === 2) {
						// 余额支付
						this.balancePayment(this.orderNum, addressId, couponId);
					} else if (this.paymentMethod === 3) {
						// 微信支付
						this.wechatPayment(this.orderNum, addressId, couponId);
					}
				} else {
					// 1. 调用sureBuyGoods接口获取订单号
					api.sureBuyGoods({
						cart_ids: this.cartIds
					}).then(res => {
						if (res.code === 1 && res.data && res.data.order_num) {
							// 保存订单号
							this.orderNum = res.data.order_num;
							const addressId = this.addressInfo.id;
							const couponId = this.selectedCoupon ? this.selectedCoupon.id : 0;

							// 2. 根据支付方式调用不同的支付接口
							if (this.paymentMethod === 1) {
								// 货到付款
								this.cashOnDelivery(this.orderNum, addressId);
							} else if (this.paymentMethod === 2) {
								// 余额支付
								this.balancePayment(this.orderNum, addressId, couponId);
							} else if (this.paymentMethod === 3) {
								// 微信支付
								this.wechatPayment(this.orderNum, addressId, couponId);
							}
						} else {
							uni.hideLoading();
							console.error('res-------------', res);
							uni.showToast({
								title: res.msg || '获取订单号失败',
								icon: 'none'
							});
						}
					}).catch(err => {
						uni.hideLoading();
						console.error('获取订单号失败', err);
						uni.showToast({
							title: err.msg || '获取订单号失败',
							icon: 'none'
						});
					});
				}
			},

			// 货到付款
			cashOnDelivery(orderNum, addressId) {
				api.cashDelivery({
					order_num: orderNum,
					address_id: addressId,
					service_start_time: 0,
					service_end_time: 0
				}).then(res => {
					uni.hideLoading();
					if (res.code === 1) {
						uni.showToast({
							title: '下单成功',
							icon: 'success'
						});
						// 跳转到订单列表页
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/index/order'
							});
						}, 1500);
					} else {
						uni.showToast({
							title: res.msg || '货到付款失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('货到付款失败', err);
					uni.showToast({
						title: '货到付款失败',
						icon: 'none'
					});
				});
			},

			// 微信支付
			wechatPayment(orderNum, addressId, couponId) {
				api.payOrder({
					order_sn: orderNum,
					pay_type: 4,
					address_id: addressId,
					coupon_id: couponId,
					service_start_time: 0,
					service_end_time: 0
				}).then(res => {
					uni.hideLoading();
					if (res.code === 1 && res.data) {
						var payData = res.data;
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: payData.timeStamp.toString(),
							nonceStr: payData.nonceStr,
							package: payData.package,
							signType: payData.signType,
							paySign: payData.sign,
							success: (res) => {
								uni.showToast({
									title: '支付成功',
									icon: 'success'
								});
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/index/order'
									});
								}, 1500);
							},
							fail: (err) => {
								uni.showToast({
									title: '支付取消',
									icon: 'none'
								});
							}
						});
					} else {
						uni.showToast({
							title: res.msg || '微信支付失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('微信支付失败', err);
					uni.showToast({
						title: '微信支付失败',
						icon: 'none'
					});
				});
			},

			// 余额支付
			balancePayment(orderNum, addressId, couponId) {
				// 弹出输入密码的弹窗
				uni.showModal({
					title: '余额支付',
					content: '',
					editable: true,
					placeholderText: '请输入登录密码',
					success: (res) => {
						if (res.confirm && res.content) {
							const payPwd = res.content;
							// 调用余额支付接口
							api.balancePayGoods({
								order_num: orderNum,
								address_id: addressId,
								coupon_id: couponId,
								pay_pwd: payPwd,
								service_start_time: 0,
								service_end_time: 0
							}).then(res => {
								uni.hideLoading();
								if (res.code === 1) {
									uni.showToast({
										title: '支付成功',
										icon: 'success'
									});
									// 跳转到订单列表页
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/index/order'
										});
									}, 1500);
								} else {
									uni.showToast({
										title: res.msg || '余额支付失败',
										icon: 'none'
									});
								}
							}).catch(err => {
								uni.hideLoading();
								console.error('余额支付失败', err);
								uni.showToast({
									title: err.msg || '余额支付失败',
									icon: 'none'
								});
							});
						} else {
							uni.hideLoading();
						}
					},
					fail: () => {
						uni.hideLoading();
					}
				});
			},

			// 设置选中的地址ID
			setSelectedAddressId(addressId) {
				console.log('设置选中的地址ID:', addressId);
				// 在地址列表中查找对应的地址信息
				if (this.addressList && this.addressList.length > 0) {
					const selectedAddress = this.addressList.find(item => item.id === addressId);
					if (selectedAddress) {
						this.addressInfo = selectedAddress;
					} else {
						console.error('未找到对应的地址信息');
					}
				} else {
					// 如果地址列表为空，先获取地址列表再设置
					this.getAddressLists().then(() => {
						if (this.addressList && this.addressList.length > 0) {
							const selectedAddress = this.addressList.find(item => item.id === addressId);
							if (selectedAddress) {
								this.addressInfo = selectedAddress;
							}
						}
					});
				}
			}
		},

	};
</script>

<style lang="scss">
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	// 主内容区
	.main-content {
		flex: 1;
		padding-bottom: 120rpx; // 为底部支付栏预留空间

		.section-title {
			padding: 20rpx 30rpx;
			font-size: 28rpx;
			color: #333;
			background-color: #f5f5f5;
		}

		// 地址区域
		.address-section {
			background-color: #fff;
			margin-bottom: 20rpx;

			.address-info {
				padding: 20rpx 30rpx;

				.consignee {
					font-size: 30rpx;
					color: #333;
					margin-bottom: 10rpx;
					display: block;
				}

				.address-detail {
					font-size: 28rpx;
					color: #666;
					line-height: 1.5;
					display: block;
				}
			}

			.no-address {
				padding: 40rpx 30rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				text {
					font-size: 28rpx;
					color: #999;
				}

				.all-evaluate {
					font-size: 28rpx;
					color: #999;
					margin-left: 10rpx;
					padding-right: 10rpx;
				}
			}
		}

		// 商品列表区域
		.goods-section {
			background-color: #fff;
			margin-bottom: 20rpx;

			.goods-list {
				padding: 0 30rpx;

				.goods-item {
					display: flex;
					padding: 20rpx 0;
					border-bottom: 1rpx solid #eee;

					&:last-child {
						border-bottom: none;
					}

					.goods-image {
						width: 160rpx;
						height: 160rpx;
						border-radius: 10rpx;
						margin-right: 20rpx;
					}

					.goods-info {
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: space-between;

						.goods-name {
							font-size: 30rpx;
							color: #333;
							margin-bottom: 5rpx;
							display: -webkit-box;
							-webkit-line-clamp: 1;
							-webkit-box-orient: vertical;
							overflow: hidden;
						}

						.goods-desc {
							font-size: 26rpx;
							color: #666;
							margin-bottom: 5rpx;
						}

						.goods-spec {
							font-size: 26rpx;
							color: #666;
							margin-bottom: 5rpx;
						}

						.goods-price {
							display: flex;
							align-items: center;

							.sell-price {
								font-size: 30rpx;
								color: #e64340;
							}

							.original-price {
								font-size: 24rpx;
								color: #999;
								text-decoration: line-through;
								margin-left: 10rpx;
							}
						}

						.goods-amount {
							font-size: 26rpx;
							color: #666;
							align-self: flex-end;
						}
					}
				}
			}
		}

		// 支付方式区域
		.payment-section {
			background-color: #fff;
			margin-bottom: 20rpx;

			.payment-methods {
				padding: 0 30rpx;

				.method-item {
					display: flex;
					align-items: center;
					padding: 20rpx 0;
					border-bottom: 1rpx solid #eee;

					&:last-child {
						border-bottom: none;
					}

					.method-icon {
						width: 40rpx;
						height: 40rpx;
						margin-right: 20rpx;
					}

					text {
						font-size: 30rpx;
						color: #333;
						flex: 1;
					}

					.check-icon {
						width: 30rpx;
						height: 30rpx;
					}

					&.active {
						color: #e64340;
					}
				}
			}
		}

		// 优惠券区域
		.coupon-section {
			background-color: #fff;
			margin-bottom: 20rpx;

			.coupon-info {
				padding: 20rpx 30rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				text {
					font-size: 30rpx;
					color: #333;
				}
			}

			.coupon-discount {
				padding: 0 30rpx 20rpx;

				text {
					font-size: 28rpx;
					color: #e64340;
				}
			}
		}


	}

	// 底部支付栏
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		border-top: 1rpx solid #eee;

		.price-info {
			text {
				font-size: 28rpx;
				color: #333;
			}

			.total-price {
				font-size: 36rpx;
				color: #e64340;
				font-weight: bold;
				margin: 0 5rpx;
			}

			.discount-price {
				font-size: 28rpx;
				color: #666;
			}
		}

		.pay-btn {
			width: 280rpx;
			height: 80rpx;
			background-color: #e64340;
			color: #fff;
			font-size: 32rpx;
			text-align: center;
			line-height: 80rpx;
			border-radius: 40rpx;
		}
	}
</style>